<template>
  <el-dialog v-model="visible" title="📝 用户注册" width="400px" @close="resetForm">
    <el-form :model="form" label-width="70px">
      <el-form-item label="用户名">
        <el-input v-model="form.username" />
      </el-form-item>

      <el-form-item label="密码">
        <el-input v-model="form.password" type="password" show-password />
      </el-form-item>

      <el-form-item label="确认密码">
        <el-input v-model="form.confirmPassword" type="password" show-password />
      </el-form-item>

      <el-form-item label="角色">
        <el-select v-model="form.role" placeholder="请选择角色">
          <el-option label="学生" value="ROLE_STUDENT" />
          <el-option label="教师" value="ROLE_TEACHER" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitRegister">注册</el-button>
    </template>
  </el-dialog>
</template>


<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { registerUser } from '@/api/user'

const visible = defineModel()

const form = ref({
  username: '',
  password: '',
  confirmPassword: '',
  role: '',
})

const resetForm = () => {
  form.value.username = ''
  form.value.password = ''
  form.value.confirmPassword = ''
  form.value.role = ''
}

const submitRegister = async () => {
  if (!form.value.username || !form.value.password || !form.value.confirmPassword || !form.value.role) {
    ElMessage.warning('请完整填写所有信息')
    return
  }

  if (form.value.password !== form.value.confirmPassword) {
    ElMessage.error('两次密码输入不一致')
    return
  }

  try {
    const res = await registerUser(form.value)
    console.log(res)
    ElMessage.success('注册成功，请登录')
    visible.value = false
  } catch (e) {
    ElMessage.error(`注册失败：${e.message}`)
  }
}
</script>

